<?php

class User extends Controller {

        /**
         * User class constructor.
         */
	function User()
	{
		parent::Controller();
                $this->load->helper(array('url', 'form'));

                //Redirect those not logged in
                if($this->session->userdata('username'))
                    redirect(base_url() . 'index.php/home');
	}

        /**
         * Index page method.
         */
	function index()
	{
                $data['content'] = 'frontpage_content';
                $data['form_attributes'] = array('name' => 'loginForm');
		$this->load->view('login_template', $data);
	}

        /**
         * Method for adding a new user.
         */
        function newuser()
        {
                $data['content'] = 'newuser_form';

                //Set attributes for the state field
                $data['state_attributes'] = array(
                                                    'name' => 'state',
                                                    'maxlength' => '2',
                                                    'size' => '2'
                                                 );
                $data['form_attributes'] = array('name' => 'loginForm');

                //Check to see if the user is accessing the form, or submitting it
                if(!$this->input->post('postback'))
                {
                    $this->load->view('login_template', $data);
                }

                else
                {
                    $this->load->model('UserModel');

                    //Begin the form validation process
                    $this->load->library('form_validation');
                        
                    //Set the validation rules
                    $this->form_validation->set_rules('username', 'Username', 'trim|required|max_length[20]|callback_usrname_dup_validator');
                    $this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[5]|max_length[20]|matches[passwordconf]');
                    $this->form_validation->set_rules('fname', 'First Name', 'trim|required|max_length[30]');
                    $this->form_validation->set_rules('lname', 'Last Name', 'trim|required|max_length[30]');
                    $this->form_validation->set_rules('email', 'Email Address', 'trim|required|max_length[50]|valid_email');
                    $this->form_validation->set_rules('city', 'City', 'trim|required|max_length[30]');
                    $this->form_validation->set_rules('state', 'State', 'trim|required|max_length[2]');

                    $this->form_validation->set_message('matches', 'The passwords you entered did not match.');

                    //Send back to the form to display errors
                    if($this->form_validation->run() == FALSE)
                    {
                        $this->load->view('login_template', $data);
                    }
                    else
                    {
                        //Load POST data into an array.
                        $userData = array();
                        $userData['username'] = $this->input->post('username');
                        $userData['password'] = $this->encrypt->sha1($this->input->post('password'));
                        $userData['fname'] = $this->input->post('fname');
                        $userData['lname'] = $this->input->post('lname');
                        $userData['email'] = $this->input->post('email');
                        $userData['city'] = $this->input->post('city');
                        $userData['state'] = $this->input->post('state');

                        //Insert the data
                        $this->UserModel->addNewAccount($userData);

                        //Log the user in and send them to their account
                        $sessiondata = array('username' => $this->input->post('username'));
                        $this->session->set_userdata($sessiondata);

                        $data['content'] = 'newuser_added';
                        $this->load->view('login_template', $data);
                    }         

                }
        }

        /**
         * Method for processing a user login.
         */
        function login()
        {
                $this->load->library('form_validation');

                //Data to be sent to the view for ALL conditional branches
                $data['content'] = 'frontpage_content';
                $data['form_attributes'] = array('name' => 'loginForm');

                $this->load->model('UserModel', '', TRUE);

                $this->form_validation->set_rules('loginusername', 'Username', 'trim');
                $this->form_validation->set_rules('loginpassword', 'Password', 'trim');

                if($this->form_validation->run() == FALSE)
                {
                   $this->load->view('login_template', $data);
                }
                //Check user credentials and login
                else
                {

                    if(!$this->UserModel->checkCredentials($this->input->post('loginusername'),$this->encrypt->sha1($this->input->post('loginpassword'))))
                    {
                        $data['login_error'] = 'Your username <br />and/or password<br /> was not found.';

                        $this->load->view('login_template', $data);
                    }
                    else
                    {
                        $sessiondata = array('username' => $this->input->post('loginusername'));

                        //Add session data
                        $this->session->set_userdata($sessiondata);

                        redirect(base_url() . 'index.php/home');
                    }


                }


        }

        /**
         * Custom validator method for determining if a username already
         * exists within the database.
         * @param string $user
         * @return boolean
         */
        function usrname_dup_validator($user)
        {
            $this->load->model('UserModel');

            $ret = $this->UserModel->checkForDuplicate($user);

            //If the username exists, set the error message
            if($ret == FALSE)
            {
                $this->form_validation->set_message('usrname_dup_validator', 'The username you choose is already taken.');
            }
            return $ret;
        }


}
?>
